package com.qf.common.exception;

import com.qf.common.core.domain.ResponseCode;
import com.qf.common.core.domain.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

/**
 * @Author: sin
 * @Date: 2024/10/10 18:59
 * @Description: 全局异常
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public ResponseResult<Object> baseExceptionHandler(BaseException e) {
        return ResponseResult.fail(e.getCode(), e.getErrMessage());
    }

    /**
     * 处理参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult<Object> handleValidationExceptions(MethodArgumentNotValidException e) {
        String msg  =e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return ResponseResult.fail(ResponseCode.VALID_ERROR.getCode(), msg == null ? ResponseCode.VALID_ERROR.getDesc() : msg);
    }

    @ExceptionHandler({AccessDeniedException.class})
    @ResponseBody
    public ResponseResult<Object> throwAccessDeniedException(AccessDeniedException e) throws AccessDeniedException {
        log.info("权限不足：" + e.getMessage());
        return ResponseResult.fail(e.getMessage());
    }

    /**
     * 处理其余异常
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseResult<Object> otherExceptionHandler(RuntimeException e) {
        return ResponseResult.fail(e.getMessage());
    }

}
